package com.aluvfy.jdbc;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ResourceBundle;

/*
* Description: 获取结果数据集元数据信息--通过ResultSetMetaData
* */
public class JDBCTest05 {
    public static void main(String[] args) {
        //读取属性配置文件，读取数据库连接
        ResourceBundle bundle = ResourceBundle.getBundle("com.aluvfy.jdbc.jdbc");
        String driver = bundle.getString("driver");
        String url = bundle.getString("url");
        String user = bundle.getString("user");
        String password = bundle.getString("password");

        Connection conn = null;
        Statement stm = null;
        ResultSet rs = null;

        //ctrl alt t 异常处理
        try {
            //1. 注册驱动
            Class.forName(driver);
            //2. 获取连接
            conn = DriverManager.getConnection(url, user, password);
            //3. 获取数据库操作对象
            stm = conn.createStatement();
            //4. 执行sql语句
            String sql = "select * from t_product";
            rs = stm.executeQuery(sql);
            //5. 处理查询结果集
            //通过ResultSet来获取结果集元数据ResultSetMateData
            //再通过结果集元数据信息来获取列的信息，如列名、列的数据蕾西、列的长度等
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            System.out.println("总列数：" + columnCount);
            for (int i = 1; i <= columnCount; i++) {
                //JDBC中所有下标从1开始
                //获取列名
                String columnName = rsmd.getColumnName(i);
                //获取列的数据类型
                String columnType = rsmd.getColumnTypeName(i);
                //获取列的长度
                int columnLength = rsmd.getColumnDisplaySize(i);
                System.out.println(i + ":" + columnName + ":" + columnType + ":" + columnLength);
            }

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //6. 关闭资源
            try {
                if (rs != null) rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                if (stm != null) stm.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                if (conn != null) conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
